package com.example.demojimmer.domain.userauth.handler;

import cn.hutool.json.JSONUtil;
import com.example.demojimmer.application.dto.Results;
import com.example.demojimmer.domain.userauth.exception.JwtException4010;
import com.example.demojimmer.domain.userauth.exception.JwtException4011;
import com.example.demojimmer.domain.userauth.state.RespEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 未认证的 请求处理器
 */
@Slf4j
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        log.error("token错误或者过期,{}", e.getMessage(), e);
        log.error("请求uri【{}】", request.getRequestURI());
        Results results = new Results();

        if (e instanceof JwtException4010) {
            results.setCode(RespEnum.JWTEXECEPTION4010.getCode());
            results.setMsg(RespEnum.JWTEXECEPTION4010.getDescribe());
        } else if (e instanceof JwtException4011) {
            results.setCode(RespEnum.JWTEXECEPTION4011.getCode());
            results.setMsg(RespEnum.JWTEXECEPTION4011.getDescribe());
        }
        
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        response.getWriter().write(JSONUtil.toJsonStr(results));
    }

}
